<?php

namespace app\admin\model\shopro;

use think\Model;


class Storearea extends Model
{

    

    

    // 表名
    protected $name = 'store_area';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text',
        'bindtime_text'
    ];

    protected static function init()
    {
        self::beforeInsert(function($data){


            if($data['userid'])
            {
                $data->status = 1;
                $data->bindtime = time();
            }
        });
        self::beforeUpdate(function($data){
            $row = self::get($data->id);
            if($data->userid && $data->userid != $row->userid)
            {
                $data->status = 1;
                $data->bindtime = time();
            }
            if(!$data->userid)
            {
                $data->status = 0;
                $data->bindtime = 0;
            }
        });
    }
    
    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ?: ($data['status'] ?? '');
        $list = $this->getStatusList();
        return $list[$value] ?? '';
    }


    public function getBindtimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['bindtime'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setBindtimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function user()
    {
        return $this->belongsTo('app\admin\model\User', 'userid', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
